import {ref} from 'vue'

export default async function() {
	//摄像头列表
	const cameras = ref([])
	let stream = null

	try {
		console.log('正在获取摄像头列表...')
		// 检查浏览器是否支持MediaDevices API
		if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
			console.error('当前浏览器不支持设备枚举功能')
			throw new Error('当前浏览器不支持设备枚举功能')
		}

		// 先请求媒体权限，否则可能获取不到设备标签
		console.log('请求摄像头访问权限...')

		// 添加重试机制
		let retries = 0;
		const maxRetries = 2;
		let lastError = null;

		while (retries <= maxRetries && !stream) {
			try {
				stream = await navigator.mediaDevices.getUserMedia({
					video: {
						width: { ideal: 640 },
						height: { ideal: 480 }
					},
					audio: false
				})
				console.log('摄像头访问权限已获取')
				break;
			} catch (error) {
				lastError = error;
				console.warn(`获取摄像头权限失败 (尝试 ${retries + 1}/${maxRetries + 1})`, error)
				retries++;

				// 短暂延时后重试
				if (retries <= maxRetries) {
					console.log(`等待 1 秒后重试...`)
					await new Promise(resolve => setTimeout(resolve, 1000));
				}
			}
		}

		if (!stream) {
			throw lastError || new Error('无法访问摄像头，请检查权限设置');
		}

		// 获取所有可用的媒体设备
		const devices = await navigator.mediaDevices.enumerateDevices()
		console.log('获取到所有媒体设备:', devices)

		// 过滤出视频输入设备(摄像头)
		const videoDevices = devices.filter(device => device.kind === 'videoinput')
		console.log('过滤出视频设备:', videoDevices)

		if (videoDevices.length === 0) {
			console.warn('未检测到视频设备')
		}

		// 格式化摄像头列表数据
		cameras.value = videoDevices.map(device => ({
			deviceId: device.deviceId,
			label: device.label || `摄像头 ${cameras.value.length + 1}`
		}))

		console.log('格式化后的摄像头列表:', cameras.value)
		return cameras
	} catch (error) {
		console.error('获取摄像头列表失败:', error)
		return ref([])
	} finally {
		// 释放摄像头资源
		if (stream) {
			stream.getTracks().forEach(track => track.stop())
			stream = null
		}
	}
}